package io.renren.modules.api.controller;

import java.util.*;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import io.renren.common.annotation.SysLog;
import io.renren.common.exception.RRException;
import io.renren.common.utils.DateUtils;
import io.renren.common.utils.FileUtils;
import io.renren.common.validator.Assert;
import io.renren.common.validator.ValidatorUtils;
import io.renren.modules.api.entity.DnsParsingEntity;
import io.renren.modules.api.service.DnsParsingService;
import io.renren.modules.sys.shiro.ShiroUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.renren.modules.api.entity.WeixinNoEntity;
import io.renren.modules.api.service.WeixinNoService;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;

/**
 * 
 *
 * @author owen
 * @email zhaoouyang@qq.com
 * @date 2018-05-29 15:20:48
 */
@RestController
@RequestMapping("api/weixinno")
public class WeixinNoController {
    @Autowired
    private WeixinNoService weixinNoService;

    @Autowired
    private DnsParsingService dnsParsingService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("api:weixinno:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = weixinNoService.queryPage(params);
        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("api:weixinno:info")
    public R info(@PathVariable("id") Integer id){
        WeixinNoEntity weixinNo = weixinNoService.selectById(id);
        weixinNo.setOldwxno(null);
        return R.ok().put("weixinNo", weixinNo);
    }

    /**
     * 保存
     */
    @SysLog("保存微信推广链接")
    @RequestMapping("/save")
    @RequiresPermissions("api:weixinno:save")
    public R save(@RequestBody WeixinNoEntity weixinNo){
        weixinNo.setCreatetime(DateUtils.getTime());
        weixinNo.setOperater(ShiroUtils.getUserEntity().getUsername());
        weixinNoService.insert(weixinNo);
        return R.ok();
    }

    /**
     * 修改
     */
    @SysLog("修改微信推广链接")
    @RequestMapping("/update")
    @RequiresPermissions("api:weixinno:update")
    public R update(@RequestBody WeixinNoEntity weixinNo) throws Exception {
        ValidatorUtils.validateEntity(weixinNo);
        weixinNo.setOperater(ShiroUtils.getUserEntity().getUsername());
        weixinNo.setUpdatetime(DateUtils.getTime());

        weixinNoService.updateWxnoAndImage(weixinNo); //修改服务器内部文件的
        weixinNoService.updateAllColumnById(weixinNo);//全部更新
        return R.ok();
    }

    /**
     * 删除
     */
    @SysLog("删除微信推广链接")
    @RequestMapping("/delete")
    @RequiresPermissions("api:weixinno:delete")
    public R delete(@RequestBody Integer[] ids){
        weixinNoService.deleteBatchIds(Arrays.asList(ids));
        return R.ok();
    }


    /**
     * 导入url
     * 1 根据域名id查询服务器路径（path），以及状态(import)
     * 2 如果未导入，则递归所有文件找出所有.html文件数据 存入域名表
     * 3 成功导入，修改导入状态
     */
    @SysLog("初次导入域名链接")
    @RequestMapping("/importUrl/{id}")
    @RequiresPermissions("api:weixinno:list")
    @Transactional
    public R importUrl(@PathVariable("id") Integer id) throws Exception {

        DnsParsingEntity dnsParsing = dnsParsingService.selectById(id);
        String operater= ShiroUtils.getUserEntity().getUsername();
        Assert.isNull(dnsParsing,"暂无该域名");

        //递归跟目录下的子目录 并且插入数据
        List<WeixinNoEntity> list=new ArrayList<WeixinNoEntity>();
        FileUtils.recursiveFiles(dnsParsing.getPath(),dnsParsing,list,operater);

        if(dnsParsing.getStatus()==1){
            for(int i=0;i<list.size();i++){
                String allurl=list.get(i).getAllurl();

                Wrapper<WeixinNoEntity> wrapper=new EntityWrapper<WeixinNoEntity>();
                wrapper.and().eq(StringUtils.isNotBlank(allurl),"allurl",allurl);
                WeixinNoEntity  weixinNoEntity= weixinNoService.selectOne(wrapper);

                // 如果查询不到则插入
                if(weixinNoEntity==null){
                    weixinNoService.insert(list.get(i));
                }else{
                // 如果能查询的到则更新
                    weixinNoEntity.setWxno(null);
                    weixinNoEntity.setPicture(null);
                    weixinNoEntity.setLinkurl(list.get(i).getLinkurl());
                    weixinNoEntity.setDnsname(list.get(i).getDnsname());
                    weixinNoEntity.setPath(list.get(i).getPath());
                    weixinNoEntity.setDnsid(list.get(i).getDnsid());
                    weixinNoEntity.setUrl(list.get(i).getUrl());
                    weixinNoService.updateById(weixinNoEntity);
                }
            }
            return R.ok("刷新成功");
        }else{
            try {
                //weixinNoService.insertOrUpdateAllColumnBatch(list);
                weixinNoService.insertOrUpdateAllColumnBatch(list);
                //修改状态为已导入
                DnsParsingEntity ds=new DnsParsingEntity();
                ds.setId(id);
                ds.setStatus(1);
                dnsParsingService.updateById(ds);
            }catch (MybatisPlusException e){
                e.printStackTrace();
                throw new RRException("该域名已导入");
            }
            return R.ok("导入成功");
        }

    }



    /**
     * 复制url
     * path:  复制的路径
     * dnsid: 域名id
     * urls:  链接 例：htttp://www.baidu.com,http://xinnang.com,http://douban.com
     * counts: 复制的数量 例：1,2,3
     * 注： urls.length 必须等于 counts.length
     */
    @SysLog("复制URL链接")
    @RequestMapping("/copyUrl")
    @RequiresPermissions("api:weixinno:list")
    @Transactional
    public R copyUrl(String urls,String dnsid,String path,String counts) throws Exception {

        Assert.isBlank(urls,"URLS不能为空");
        Assert.isBlank(dnsid,"dnsid不能为空");
        Assert.isBlank(path,"path不能为空");
        Assert.isBlank(counts,"counts不能为空");

        List<WeixinNoEntity> list=new ArrayList<WeixinNoEntity>(); //需要复制的微信链接集合
        String urlArr[]=urls.split(","); //域名 集合
        String countArr[]=counts.split(","); //域名复制数 集合



        DnsParsingEntity dnsParsing = dnsParsingService.selectById(dnsid);
        Assert.isNull(dnsParsing,"请先选择域名");

        for(int i=0;i<urlArr.length;i++){
            if(StringUtils.isNotBlank(urlArr[i])){
               Wrapper<WeixinNoEntity> wrapper=new EntityWrapper<WeixinNoEntity>().eq(StringUtils.isNotBlank(urlArr[i]),"allurl",urlArr[i]);
               WeixinNoEntity weixinNoEntity=weixinNoService.selectOne(wrapper);
               Assert.isNull(weixinNoEntity,"链接["+urlArr[i]+"]不存在，请确认后再录入");
               list.add(weixinNoEntity);
            }
        }

        //校验urls.length==counts.length
        if(urlArr.length!=countArr.length||list.size()!=countArr.length){
            throw new RRException("[域名个数]与[域名复制数个数]不匹配");
        }

        //校验复制的目的路径
        String mdPath=dnsParsing.getPath()+path;
        if(FileUtil.exist(mdPath)){
            throw new RRException("路径["+path+"]已存在，请更换其他路径");
        }

        //数据确认无误 执行复制动作
        for(int i=0;i<list.size();i++){
            Integer count=new Integer(countArr[i]); //域名复制个数
            for(int j=0;j<count;j++){
                String html=list.get(i).getLinkurl();
                String currPath=list.get(i).getLinkurl();

                if(count>1){
                    html=html.substring(0,html.length()-5);
                    html=html+"_"+j+".html";
                }
                currPath=list.get(i).getPath()+currPath;
                FileUtil.copy(currPath,mdPath+html,true); //备份
            }


            /**
             * 拷贝js css images image 文件
             */

            String html=list.get(i).getLinkurl();
            String currPath=list.get(i).getPath()+html;

            String mdDicPath=getDirectory(mdPath+html);

            String dicPath=getDirectory(currPath,"images");
            if(FileUtil.exist(dicPath)){

                FileUtil.copy(dicPath,mdDicPath,true); //备份
            }


            String dicPath_1=getDirectory(currPath,"image");
            if(FileUtil.exist(dicPath_1)){
                FileUtil.copy(dicPath_1,mdDicPath,true); //备份
            }


            String dicPath_2=getDirectory(currPath,"js");
            if(FileUtil.exist(dicPath_2)){
                FileUtil.copy(dicPath_2,mdDicPath,true); //备份
            }


            String dicPath_3=getDirectory(currPath,"css");
            if(FileUtil.exist(dicPath_3)){
                FileUtil.copy(dicPath_3,mdDicPath,true); //备份
            }

        }
        return R.ok();
    }


    /**
     * 获取文件所在目录
     * @return
     */
    public String getDirectory(String path){
        int lastindex=path.lastIndexOf("/");
        path=path.substring(0,lastindex);
        return path;
    }

    /**
     * 获取文件所在目录
     * @return
     */
    public String getDirectory(String path,String filder){
        int lastindex=path.lastIndexOf("/");
        path=path.substring(0,lastindex)+"/"+filder;
        return path;
    }


   /* *//**
     * 刷新url
     *//*
    @SysLog("刷新微信链接")
    @RequestMapping("/reloadUrl/{id}")
    @RequiresPermissions("api:weixinno:list")
    @Transactional
    public R reloadUrl(@PathVariable("id") Integer id) throws Exception {

        DnsParsingEntity dnsParsing = dnsParsingService.selectById(id);
        String operater= ShiroUtils.getUserEntity().getUsername();

        Assert.isNull(dnsParsing,"暂无该域名");

        //递归跟目录下的子目录 并且插入数据
        List<WeixinNoEntity> list=new ArrayList<WeixinNoEntity>();
        FileUtils.recursiveFiles(dnsParsing.getPath(),dnsParsing,list,operater);

        if(dnsParsing.getStatus()==1){
            for(int i=0;i<list.size();i++){
                weixinNoService.insert(list.get(i));
            }
        }else{
            try {
                //weixinNoService.insertOrUpdateAllColumnBatch(list);
                weixinNoService.insertOrUpdateBatch(list);
            }catch (MybatisPlusException e){
                throw new RRException("该域名已导入");
            }
            //修改状态为已导入
            DnsParsingEntity ds=new DnsParsingEntity();
            ds.setId(id);
            ds.setStatus(1);
            dnsParsingService.updateById(ds);
        }
        return R.ok();
    }*/

}
